from django.shortcuts import render
from django import http
from django.views import View
from apps.contents.models import GoodsCategory
from apps.goods.models import SKU
from django.core.paginator import Paginator
from apps.goods.tool import get_crumbs
from haystack.views import SearchView


# 商品列表
class GoodsListView(View):

    def get(self, request, id):

        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        if not all([page, page_size, ordering]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必须参数'})

        category3 = GoodsCategory.objects.get(id=id)

        # 获取所有category3类别的SKU
        skus = SKU.objects.filter(category=category3, is_launched=True).order_by(ordering)

        paginator = Paginator(skus, page_size)

        try:
            # 获取当前页数的所有SKU数据
            page_num_skus = paginator.page(page)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '数据错误'})

        list = []
        for sku in page_num_skus:
            list.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price
            })
        # 获取总页数
        page_sunbs = paginator.num_pages
        # 面包屑导航
        breadcrumb = get_crumbs(category3)

        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'breadcrumb': breadcrumb,
            'list': list,
            'count': page_sunbs
        })


# 热销商品
class GoodsHotView(View):

    def get(self, request, id):
        category3 = GoodsCategory.objects.get(id=id)

        skus = SKU.objects.filter(category=category3, is_launched=True).order_by('-sales')[:2]

        hot_skus = []
        for sku in skus:
            hot_skus.append(
                {
                    "id": sku.id,
                    "default_image_url": sku.default_image.url,
                    "name": sku.name,
                    "price": sku.price
                }
            )

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'hot_skus': hot_skus})


class SelfSearchView(SearchView):

    def create_response(self):
        """
        Generates the actual HttpResponse to send back to the user.
        """

        context = self.get_context()
        skus = context['page'].object_list
        sku_lsit = []
        for sku in skus:
            sku_lsit.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context['query'],
                'page_size': context['paginator'].num_pages,
                'count': context['paginator'].count,
            })
        return http.JsonResponse(sku_lsit, safe=False)
